package mephisto.services.impl;

import groovy.lang.Writable;
import groovy.text.GStringTemplateEngine;
import groovy.text.Template;
import groovy.text.TemplateEngine;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import mephisto.Context;
import mephisto.services.IGroovyService;

public class GroovyService extends BaseService implements IGroovyService {

    public GroovyService() {
        super();
    }

    public String evaluate(String content, Context context) throws Exception {
        TemplateEngine engine = new GStringTemplateEngine(getClass().getClassLoader());
        String result = null; 
        Template template = null;
        if (template == null) {
                template = engine.createTemplate(content);
                Map<String, Object> gcontext = new HashMap<String, Object>();
                // context.put("rdf", new RdfService(getContext(), getRequest(),
                // getResponse()));
                gcontext.put("utils", new Utils());
                gcontext.put("rdf", mephisto.getRdfService());
                gcontext.put("mephisto", mephisto);
                gcontext.put("base", "mephisto");
                Iterator<String> it = context.keyIterator();
                while (it.hasNext()) {
                    String key = it.next();
                    gcontext.put(key, context.get(key));
                }
                
                // context.put("oreference", originalRef);
                Writable writable = template.make(gcontext);
                result = writable.toString();

        }

        return result;
    }

    public static void main(String[] args) {

        GroovyService grr = new GroovyService();
        try {
            String output = grr.evaluate("<%  out.println(\"jeeke\"); "
                    + "int i = 0; while (i<10) {out.println(\"hibou\");i++}; "
                    + "out.println(\"smdklfj\") %>", null);
            System.out.println("Output: " + output);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
